package com.connection.second.common.utils.oss;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GetObjectRequest;
import com.connection.second.common.config.AliyunOssConfig;
import com.connection.second.common.utils.StringUtils;
import com.connection.second.common.utils.file.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author: FL
 * @Date: 2024/12/2 16:19
 **/
@Component
@Slf4j
public class AliyunOssUtils {

    private static AliyunOssConfig aliyunOssConfig;

    //设置允许上传文件格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png", ".gif", ".mp3", ".mp4", ".mkv"};


    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public AliyunOssUtils(AliyunOssConfig aliyunOssConfig) {
        AliyunOssUtils.aliyunOssConfig = aliyunOssConfig;
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {
        //审核上传文件是否符合规定格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if (!isLegal) {
            log.error("不允许上传此文件类型");
            return null;
        }
        // 生成 OSSClient
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();

        // 编码文件名
        String filePathName = FileUploadUtils.extractFilename(file);
        // 文件路径名称
        filePathName = aliyunOssConfig.getFilehost() + "/" + filePathName;
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(), filePathName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String imgUrl = aliyunOssConfig.getUrl() + "/" + filePathName;
        log.info("阿里云OSS上传成功，返回的图片地址为：{}", imgUrl);
        return imgUrl;
    }

    /**
     * @param fileUrl:
     * @param fileName:
     * @return java.io.File
     * @description
     */
    public static File downLoadOssFile(String fileUrl, String fileName) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());
        if(!isFileExist(fileName)){
            log.error("文件不存在");
            return null;
        }
        File file = new File(fileName);
        String[] array = fileUrl.split("[?]");
        fileUrl = array[0];
        //key 填写不包含 Bucket 名称在内的路径  例如 testfolder/mytest.xlsx
        String key = fileUrl.substring(fileUrl.lastIndexOf(StrUtil.SLASH) + 1);
        ossClient.getObject(new GetObjectRequest(aliyunOssConfig.getBucketName(), key), file);
        ossClient.shutdown();
        return file;
    }


    /**
     * oss中文件是否存在
     *
     * @param fileName
     * @return
     */
    public static Boolean isFileExist(String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());

        Boolean result = Boolean.FALSE;
        try {
            result = ossClient.doesObjectExist(aliyunOssConfig.getBucketName(), fileName);
        } catch (OSSException oe) {
            log.error("oss检验文件是否存在失败,Error Message:{},Error Code:{}", oe.getMessage(), oe.getErrorCode());
        } finally {
            if (ossClient != null) {
                // 关闭ossClient
                ossClient.shutdown();
            }
        }
        return result;
    }

    /**
     * 删除oss文件
     *
     * @param fileName
     */
    public static void deleteFile(String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(aliyunOssConfig.getEndpoint(), aliyunOssConfig.getAccessKeyId(), aliyunOssConfig.getAccessKeySecret());

        try {
            // 删除文件
            ossClient.deleteObject(aliyunOssConfig.getBucketName(), fileName);
        } catch (OSSException oe) {
            log.error("oss删除文件失败,Error Message:{},Error Code:{}", oe.getMessage(), oe.getErrorCode());
        } finally {
            if (ossClient != null) {
                // 关闭ossClient
                ossClient.shutdown();
            }
        }
    }
}
